package com.liyueheng.app.dataWarehouseDetail.behavior

import com.liyueheng.util.{ConfigLoader, SaveAsTable, SparkConf}
import org.apache.spark.sql.functions._
import org.apache.spark.sql.{DataFrame, SparkSession}

object HourlyActiveUser {
  def analyzeHourlyActive(): Unit = {

    println("------------------ 分析小时活跃用户 -----------------")

    val appName = ConfigLoader.getString("app.name")
    val databaseDwd = ConfigLoader.getString("databases.dwd")
    val databaseDws = ConfigLoader.getString("databases.dws")
    val spark: SparkSession = SparkConf.createSparkSession(appName)

    try {
      val userActDF = spark.table(s"$databaseDwd.user_act")

      // 要分析的行为类型列表
      val actTypes = Seq(1, 2, 3, 5)

      actTypes.foreach { actType =>
        val resultDF: DataFrame = userActDF
          .filter(col("act_type") === actType)
          .withColumn("name", substring(col("act_time"), 0, 2))
          .groupBy("name")
          .agg(count("act_time").alias("value"))
          .orderBy("name")

        SaveAsTable.saveAsTable(resultDF,s"$databaseDws.detail_hau_$actType")

//        resultDF.write.mode("overwrite").format("hive").saveAsTable(s"$databaseDws.detail_hau_$actType")
      }

    } finally {
      SparkConf.stopSparkSession(spark)
    }
  }
}
